package com.cy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.dto.UserLoginDTO;
import com.cy.entity.User;
import com.cy.mapper.UserMapper;
import com.cy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService, UserDetailsService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = selectByUsername(username);

        if (user == null) {
            throw new BadCredentialsException("登录失败，用户名不存在！");
        } else {
            List<String> permissions = selectPermissions(username);

            return org.springframework.security.core.userdetails.User.builder()
                    .username(user.getUsername())
                    .password(user.getPassword())
                    .accountExpired(false)
                    .accountLocked(false)
                    .disabled(!user.isEnable())
                    .credentialsExpired(false)
                    .authorities(permissions.toArray(new String[] {}))
                    .build();
        }
    }

    /**
     * 通过用户名查询用户信息
     * @param username 用户名
     * @return User
     */
    private User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> list = list(queryWrapper);
        if (list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 通过用户名查询用户权限
     * @param username 用户名
     * @return List<String>
     */
    private List<String> selectPermissions(String username) {
        if (username == null) {
            throw new RuntimeException("用户名不能为空");
        }
        List<String> permissions = new ArrayList<>();
        permissions.add("/user/login");
        permissions.add("/user/logout");
        return permissions;
    }

    @Override
    public void login(UserLoginDTO userLoginDTO) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(),
                userLoginDTO.getPassword()
        );

        authenticationManager.authenticate(authentication);
    }

    @Override
    public void logout() {
        // todo
    }

    @Override
    public User selectById(String userId) {
        return this.getById(userId);
    }

}